package scct.ZhuZhouXing.dao;

import scct.ZhuZhouXing.model.User;
import scct.ZhuZhouXing.utils.DBUtils;

import java.sql.*;


public class UserDao {
    //登录
    public User login(String name, String pass) {
        User user = null;
        Connection conn = DBUtils.getConnection();
        String sql = "select * from sp_user where  username=? and password=?";
        try {
            PreparedStatement pstm = conn.prepareStatement(sql);
            pstm.setString(1, name);
            pstm.setString(2, pass);
            ResultSet rs = pstm.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");
                user = new User(id, username, password);
            }
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    //注册
    public boolean addUser(String name, String pass) {
        int count = 0;
        Connection conn = DBUtils.getConnection();
        String insert = " insert into sp_user values (null,?,?)";
        try {
            PreparedStatement pstmt = conn.prepareStatement(insert);
            pstmt.setString(1, name);
            pstmt.setString(2, pass);
            count = pstmt.executeUpdate();
            DBUtils.closeConnection(conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return count == 1;
    }

}
